package com.newlink.building.userinfo.activity

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.newlink.building.common_base.base.NL_BaseActivity
import com.newlink.building.common_base.base.BaseFragment
import com.newlink.building.common_base.constant.Base_Constant
import com.newlink.building.common_base.constant.Base_RouterPath
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_MESSAGE_CLOUD_UNREAD
import com.newlink.building.common_base.event.TYPE_MESSAGE_LOCAL_UNREAD
import com.newlink.building.common_base.model.bean.MessageListArrayData
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.ToastUtils
import com.newlink.building.common_base.widget.CustomDialog
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.adapter.Module_UserInfo_ViewPagerAdapter
import com.newlink.building.userinfo.databinding.ActivityMessageCenterBinding
import com.newlink.building.userinfo.fragment.message.Module_UserInfo_FlsMsgFragment
import com.newlink.building.userinfo.fragment.message.Module_UserInfo_LocalMsgFragment
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

var tabArray = mutableListOf<String>()

/**
 * @author wangyang
 * @date 2022/9/19
 * @description 我的-消息中心页面
 */
@Route(path = Base_RouterPath.PATH_MSG_TAB)
class MessageCenterActivityNL : NL_BaseActivity(),
    View.OnClickListener {

    private var curList: MutableList<MessageListArrayData> = ArrayList()
    private var mAdapter: Module_UserInfo_ViewPagerAdapter? = null
    private lateinit var mLocalMsgFragment: Module_UserInfo_LocalMsgFragment
    private lateinit var mFlsMsgFragment: Module_UserInfo_FlsMsgFragment

    private var mMessageCount = 0
    private var mNoticeCount = 0

//    override fun attachLayoutRes(): Int {
//        return R.layout.activity_message_center
//    }

    private lateinit var mBinding: ActivityMessageCenterBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityMessageCenterBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun allowFontScale() = false

    override fun initData() {
        mMessageCount = intent.getIntExtra(Base_Constant.KEY_MESSAGE_COUNT, 0)
        mNoticeCount = intent.getIntExtra(Base_Constant.KEY_NOTICE_COUNT, 0)
        tabArray = mutableListOf<String>(
            getString(R.string.message_tab_local),
            getString(R.string.message_tab_system),
        )
        mLocalMsgFragment = Module_UserInfo_LocalMsgFragment()
        mFlsMsgFragment = Module_UserInfo_FlsMsgFragment()

        val list = mutableListOf<BaseFragment>()

        if (userInfoData.prjType == 1 || userInfoData.userCategory == 2 || userInfoData.userCategory == 3) {
//            list.add(mLocalMsgFragment)
            list.add(mFlsMsgFragment)
            mBinding.msgTabLayout.visibility = View.GONE
        } else {
            list.add(mLocalMsgFragment)
            list.add(mFlsMsgFragment)
            mBinding.msgTabLayout.visibility = View.VISIBLE

        }
        mAdapter = Module_UserInfo_ViewPagerAdapter(supportFragmentManager, lifecycle)
        mAdapter?.setFragments(list)

        mBinding.msgViewPager.adapter = mAdapter
        mBinding.msgViewPager.isUserInputEnabled = false

        val curPage = intent.getIntExtra("PAGE", 0)

        if (userInfoData.prjType != 1 && curPage == 1 && list.size > 1) {
            mBinding.msgViewPager.setCurrentItem(curPage, false)
        }

        TabLayoutMediator(mBinding.msgTabLayout, mBinding.msgViewPager) { tab, position ->
            val badge = LayoutInflater.from(this).inflate(R.layout.badge_layout, null) as View
            var rootView = badge.findViewById<ConstraintLayout>(R.id.rootView)
            badge.findViewById<TextView>(R.id.contentView).text = tabArray[position]
            val layoutParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
            )
            val screenWidth = resources.displayMetrics.widthPixels
            val tabWidth = screenWidth / list.size
            //设置rootView最小宽度
            rootView.minWidth = tabWidth

            badge.layoutParams = layoutParams
            tab.customView = badge
            tab.view.setPadding(0, 0, 0, 0)

            if (position == curPage) {
                tab.customView?.findViewById<TextView>(R.id.contentView)?.setTextColor(
                    ContextCompat.getColor(
                        this@MessageCenterActivityNL,
                        R.color.white
                    )
                )
            } else {
                tab.customView?.findViewById<TextView>(R.id.contentView)?.setTextColor(
                    ContextCompat.getColor(
                        this@MessageCenterActivityNL,
                        R.color.white_60
                    )
                )
            }
        }.attach()


        mBinding.msgTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                val tabTitle = tab.customView?.findViewById<TextView>(R.id.contentView)
                tabTitle?.setTextColor(
                    ContextCompat.getColor(
                        this@MessageCenterActivityNL,
                        R.color.white
                    )
                )
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                val tabTitle = tab.customView?.findViewById<TextView>(R.id.contentView)
                tabTitle?.setTextColor(
                    ContextCompat.getColor(
                        this@MessageCenterActivityNL,
                        R.color.white_60
                    )
                )
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
                // 可选: 处理重新选中 Tab 的逻辑
            }
        })

        updateBadge(0, mMessageCount)
        updateBadge(1, mNoticeCount)
    }

    override fun initView() {
        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.message_center)
        findViewById<TextView>(R.id.tv_title_bar_right).text =
            resources.getText(R.string.message_center_clear_all)
        findViewById<TextView>(R.id.tv_title_bar_right).visibility = View.VISIBLE
        findViewById<TextView>(R.id.tv_title_bar_right).setOnClickListener(this)

    }

    private fun updateBadge(tabIndex: Int, count: Int) {
        val tab = mBinding.msgTabLayout.getTabAt(tabIndex)
        val badge = tab?.customView?.findViewById<TextView>(R.id.badgeView)
        badge?.let {
            if (count > 0) {
                it.visibility = View.VISIBLE
            } else {
                it.visibility = View.GONE
            }
        }
    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        curList?.get(requestCode).readFlag = true
//        mAdapter?.notifyDataSetChanged()
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: MessageEvent) {
        if (event.msgType == TYPE_MESSAGE_LOCAL_UNREAD) {
            val which = event.msgContent as Int
            updateBadge(0, which)
        } else if (event.msgType == TYPE_MESSAGE_CLOUD_UNREAD) {
            val which = event.msgContent as Int
            updateBadge(1, which)
        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_title_bar_right -> {
                NLog.e("[jake]----- delete all ----------")
                //全部清除
                if (userInfoData.prjType == 1) {
                    if (mFlsMsgFragment.isCurListNull()) {
                        ToastUtils.showTextToast(getString(R.string.user_msg_none_need_delete))
                        return
                    }
                } else {
                    if (mBinding.msgViewPager.currentItem == 0) {
                        if (mLocalMsgFragment.isCurListNull()) {
                            ToastUtils.showTextToast(getString(R.string.user_msg_none_need_delete))
                            return
                        }
                    } else {
                        if (mFlsMsgFragment.isCurListNull()) {
                            ToastUtils.showTextToast(getString(R.string.user_msg_none_need_delete))
                            return
                        }
                    }
                }
                CustomDialog(this).setMessage(getString(R.string.message_center_clear_all_confirm))
                    .setPositiveButton(object : CustomDialog.OnClickListener {
                        override fun onClick(dialog: CustomDialog) {
                            if (userInfoData.prjType == 1) {
                                mFlsMsgFragment.deleteAllMessageList()
                            } else {
                                if (mBinding.msgViewPager.currentItem == 0) {
                                    mLocalMsgFragment.deleteAllMessageList()
                                } else {
                                    mFlsMsgFragment.deleteAllMessageList()
                                }
                            }
                            dialog.dismiss()
                        }
                    }).setNegativeButton(object : CustomDialog.OnClickListener {
                        override fun onClick(dialog: CustomDialog) {
                            dialog.dismiss()
                        }
                    }).show()
            }
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        initData()
    }

    override fun onDestroy() {
        super.onDestroy()
    }

}